package com.zhangyj.dao;

import java.io.Reader;
import java.sql.Connection;
import java.util.Hashtable;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.zhangyj.impl.dao.BoastSqlSessionFactoryBuilder;

public class DaoManager {
	private static SqlSessionFactory factory;
	private static Hashtable<String, Object> daos;
	static {
		try {
			SqlSessionFactoryBuilder builder = new BoastSqlSessionFactoryBuilder();
			Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
			factory = builder.build(reader);
			
		} catch (Exception e) {
			throw new RuntimeException("Something bad happened while building the SqlMapClient instance." + e, e);

		}
	}

	public static SqlSessionFactory getSqlSessionFactory() {
		return factory;
	}

	public static SqlSession getSqlSession() {
		SqlSessionFactory ssf = getSqlSessionFactory();
		return ssf.openSession(true);
	}

	public static SqlSession getSqlSession(Connection conn) {
		SqlSessionFactory ssf = getSqlSessionFactory();
		return ssf.openSession(conn);
	}
	public static void closeSqlSession(SqlSession ss) {
		if (ss != null) {
			ss.close();
		}
	}
	public static <T> T getMapper(Class<T> t) {
		return getSqlSession().getMapper(t);
	}

	public static <T> T getMapper(Class<T> t, Connection conn) {
		return getSqlSession(conn).getMapper(t);
	}

	public static <T> T getDao(Class<T> t) {
		return t.cast(daos.get(t.getName()));
	}
}
